package com.qf.java2106.consumer.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ghy
 * @version 1.0
 * @date 2022-01-17
 **/
@RestController
@RequestMapping("/resttemplate")
public class RestTemplateController {

    @Autowired
    RestTemplate restTemplate;

    @Value("${server.port}")
    String port;

    @GetMapping("/get1")
    public String get1(Integer id, String name){

        String url = "http://localhost:8001/pro/device/get/resttemplate?id={id}&name={name}";

        String result = restTemplate.getForObject(url, String.class, id, name);

        return port + "-->" + result;
    }

    @GetMapping("/get2")
    public String get2(Integer id, String name){

        String url = "http://localhost:8001/pro/device/get/resttemplate?id={id}&name={name}";

        Map<String,Object> map = new HashMap<>();
        map.put("id", id);
        map.put("name", name);

        String result = restTemplate.getForObject(url, String.class, map);

        return port + "-->" + result;
    }

    @GetMapping("/get3")
    public String get3(Integer id, String name){

        String url = "http://localhost:8001/pro/device/get/resttemplate?id={id}&name={name}";

        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class, id, name);
        //响应头
        HttpHeaders headers = responseEntity.getHeaders();
        System.out.println("headers = " + headers);
        //响应行
        HttpStatus statusCode = responseEntity.getStatusCode();
        System.out.println("statusCode = " + statusCode);
        //响应体
        String result = responseEntity.getBody();

        return port + "-->" + result;
    }


    @PostMapping("/postcookie")
    public String postCookie(Integer id, String name,
                             @CookieValue(name = "login_token", required = false) String loginToken){

        String url = "http://localhost:8001/pro/device/post/resttemplate?id={1}&name={2}";

        //携带Cookie
        HttpHeaders headers = new HttpHeaders();
        List<String> cookies = new ArrayList<>();
        cookies.add("token=" + loginToken);
        headers.put("Cookie", cookies);
        //HttpHeaders implements MultiValueMap<String, String>
        //HttpEntity(MultiValueMap<String, String> headers)
        HttpEntity request = new HttpEntity(headers);

        String result = restTemplate.postForObject(url, request, String.class, id, name);

        return port + "-->" + result;
    }


}
